<!-- src/views/company/EvaluationManagement.vue -->
<template>
  <div class="evaluation-management">
    <div class="header">
      <h2>实习生评分管理</h2>
    </div>

    <!-- 筛选条件 -->
    <el-card class="filter-card">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input
            v-model="searchParams.keyword"
            placeholder="搜索学生姓名或岗位名称"
            clearable
            @clear="resetSearch"
            @keyup.enter="fetchEvaluations"
          >
            <template #append>
              <el-button icon="Search" @click="fetchEvaluations" />
            </template>
          </el-input>
        </el-col>

        <el-col :span="6">
          <el-select
            v-model="searchParams.status"
            placeholder="实习状态"
            clearable
            @change="fetchEvaluations"
          >
            <el-option label="全部" value="" />
            <el-option label="未开始" :value="0" />
            <el-option label="进行中" :value="1" />
            <el-option label="已完成" :value="2" />
            <el-option label="已终止" :value="3" />
          </el-select>
        </el-col>

        <el-col :span="6">
          <el-button @click="resetSearch">重置</el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 评分列表 -->
    <el-card>
      <el-table
        :data="evaluations"
        v-loading="loading"
        style="width: 100%"
      >
        <el-table-column prop="studentName" label="学生姓名" width="100" />
        <el-table-column prop="positionTitle" label="实习岗位" min-width="150" />
        <el-table-column prop="startDate" label="开始日期" width="120">
          <template #default="scope">
            {{ formatDate(scope.row.startDate) }}
          </template>
        </el-table-column>
        <el-table-column prop="endDate" label="结束日期" width="120">
          <template #default="scope">
            {{ formatDate(scope.row.endDate) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="实习状态" width="100">
          <template #default="scope">
            <el-tag :type="getInternshipStatusType(scope.row.status)">
              {{ getInternshipStatusLabel(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="score" label="评分" width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.score !== null" type="success">{{ scope.row.score }}</el-tag>
            <span v-else>未评分</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="viewEvaluation(scope.row)">查看详情</el-button>
            <el-button
              size="small"
              :type="scope.row.score !== null ? 'primary' : 'success'"
              @click="evaluateIntern(scope.row)"
              :disabled="![1, 2, 3].includes(scope.row.status)"
            >
              {{ scope.row.score !== null ? '重新评分' : '评分' }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :total="pagination.total"
        layout="total, prev, pager, next, jumper"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
        class="pagination"
      />
    </el-card>

    <!-- 评分对话框 -->
    <el-dialog
      v-model="evaluateDialogVisible"
      :title="isEditing ? '重新评分' : '实习生评分'"
      width="600px"
    >
      <el-form
        :model="evaluationForm"
        :rules="evaluationRules"
        ref="evaluationFormRef"
        label-width="100px"
      >
        <el-descriptions :column="2" border>
          <el-descriptions-item label="学生姓名">{{ evaluationForm.studentName }}</el-descriptions-item>
          <el-descriptions-item label="实习岗位">{{ evaluationForm.positionTitle }}</el-descriptions-item>
          <el-descriptions-item label="实习时间">
            {{ formatDate(evaluationForm.startDate) }} - {{ formatDate(evaluationForm.endDate) }}
          </el-descriptions-item>
          <el-descriptions-item label="实习状态">
            <el-tag :type="getInternshipStatusType(evaluationForm.status)">
              {{ getInternshipStatusLabel(evaluationForm.status) }}
            </el-tag>
          </el-descriptions-item>
        </el-descriptions>

        <el-form-item label="评分" prop="score">
          <el-input-number
            v-model="evaluationForm.score"
            :min="0"
            :max="100"
            controls-position="right"
            style="width: 100%"
            placeholder="请输入0-100之间的分数"
          />
        </el-form-item>

        <el-form-item label="评价" prop="comment">
          <el-input
            v-model="evaluationForm.comment"
            type="textarea"
            :rows="4"
            placeholder="请输入对实习生的评价"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="evaluateDialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="submitEvaluation"
            :loading="submitLoading"
          >
            提交评分
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 评分详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="评分详情"
      width="700px"
    >
      <div v-if="selectedEvaluation" class="evaluation-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="学生姓名">{{ selectedEvaluation.studentName }}</el-descriptions-item>
          <el-descriptions-item label="实习岗位">{{ selectedEvaluation.positionTitle }}</el-descriptions-item>
          <el-descriptions-item label="实习时间">
            {{ formatDate(selectedEvaluation.startDate) }} - {{ formatDate(selectedEvaluation.endDate) }}
          </el-descriptions-item>
          <el-descriptions-item label="实习状态">
            <el-tag :type="getInternshipStatusType(selectedEvaluation.status)">
              {{ getInternshipStatusLabel(selectedEvaluation.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="评分">
            <el-tag v-if="selectedEvaluation.score !== null" type="success">{{ selectedEvaluation.score }}</el-tag>
            <span v-else>未评分</span>
          </el-descriptions-item>
        </el-descriptions>

        <div class="comment-section" v-if="selectedEvaluation.comment">
          <h4>企业评价</h4>
          <p>{{ selectedEvaluation.comment }}</p>
        </div>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { useCompanyStore } from '../../store/company'
import { ElMessage } from 'element-plus'

const companyStore = useCompanyStore()

const evaluations = ref([])
const loading = ref(false)
const evaluateDialogVisible = ref(false)
const detailDialogVisible = ref(false)
const submitLoading = ref(false)
const isEditing = ref(false)
const evaluationFormRef = ref(null)
const selectedEvaluation = ref(null)

// 搜索参数
const searchParams = reactive({
  keyword: '',
  status: ''
})

// 分页参数
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 评分表单
const evaluationForm = reactive({
  internshipId: null,
  studentName: '',
  positionTitle: '',
  startDate: '',
  endDate: '',
  status: 0,
  score: null,
  comment: ''
})

// 表单验证规则
const evaluationRules = {
  score: [
    { required: true, message: '请输入评分', trigger: 'change' },
    { type: 'number', min: 0, max: 100, message: '评分应在0-100之间', trigger: 'change' }
  ]
}

// 获取评分列表
const fetchEvaluations = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.currentPage - 1,
      size: pagination.pageSize,
      ...searchParams
    }

    const response = await companyStore.fetchCompanyInternships(params)
    evaluations.value = response.content || response
    pagination.total = response.totalElements || 0

    // 获取评价记录并合并到实习列表中
    if (evaluations.value.length > 0) {
      const evaluationParams = {
        page: 0,
        size: 100 // 获取足够多的评价记录
      }

      const evaluationResponse = await companyStore.fetchEvaluationRecords(evaluationParams)
      const evaluationRecords = evaluationResponse.content || []

      // 将评价记录合并到实习列表中
      evaluations.value.forEach(internship => {
        const record = evaluationRecords.find(r => r.internshipId === internship.id)
        if (record) {
          internship.score = record.score
          internship.comment = record.comment
        }
      })
    }
  } catch (error) {
    ElMessage.error('获取实习列表失败: ' + (error.response?.data?.message || error.message))
  } finally {
    loading.value = false
  }
}

// 重置搜索
const resetSearch = () => {
  searchParams.keyword = ''
  searchParams.status = ''
  pagination.currentPage = 1
  fetchEvaluations()
}

// 查看评分详情
const viewEvaluation = (evaluation) => {
  selectedEvaluation.value = evaluation
  detailDialogVisible.value = true
}

// 评分实习生
const evaluateIntern = (evaluation) => {
  isEditing.value = evaluation.score !== null
  Object.assign(evaluationForm, {
    internshipId: evaluation.id,
    studentName: evaluation.studentName,
    positionTitle: evaluation.positionTitle,
    startDate: evaluation.startDate,
    endDate: evaluation.endDate,
    status: evaluation.status,
    score: evaluation.score || null,
    comment: evaluation.comment || ''
  })

  evaluateDialogVisible.value = true

  // 清除验证状态
  nextTick(() => {
    if (evaluationFormRef.value) {
      evaluationFormRef.value.clearValidate()
    }
  })
}

// 提交评分
const submitEvaluation = async () => {
  if (!evaluationFormRef.value) return

  await evaluationFormRef.value.validate(async (valid) => {
    if (valid) {
      submitLoading.value = true
      try {
        const data = {
          internshipId: evaluationForm.internshipId,
          score: evaluationForm.score,
          comment: evaluationForm.comment
        }

        await companyStore.evaluateIntern(data)
        ElMessage.success('评分提交成功')
        evaluateDialogVisible.value = false
        fetchEvaluations()
      } catch (error) {
        ElMessage.error('评分提交失败: ' + (error.response?.data?.message || error.message))
      } finally {
        submitLoading.value = false
      }
    }
  })
}

// 获取实习状态类型
const getInternshipStatusType = (status) => {
  switch (status) {
    case 0: return 'info'    // 未开始
    case 1: return 'warning' // 进行中
    case 2: return 'success' // 已完成
    case 3: return 'danger'  // 已终止
    default: return ''
  }
}

// 获取实习状态标签
const getInternshipStatusLabel = (status) => {
  switch (status) {
    case 0: return '未开始'
    case 1: return '进行中'
    case 2: return '已完成'
    case 3: return '已终止'
    default: return '未知'
  }
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleDateString()
}

// 分页处理
const handleCurrentChange = (page) => {
  pagination.currentPage = page
  fetchEvaluations()
}

const handleSizeChange = (size) => {
  pagination.pageSize = size
  pagination.currentPage = 1
  fetchEvaluations()
}

onMounted(() => {
  fetchEvaluations()
})
</script>

<style scoped>
.evaluation-management {
  padding: 20px;
}

.header {
  margin-bottom: 20px;
}

.filter-card {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.comment-section {
  margin-top: 20px;
}

.comment-section p {
  white-space: pre-wrap;
  background-color: #f5f7fa;
  padding: 10px;
  border-radius: 4px;
}
</style>
